package demo;

import com.sun.corba.se.spi.orbutil.threadpool.ThreadPool;

import java.util.concurrent.*;

/**
 * @author ：黄淼淳
 * @date ：2021/12/19 14:51
 * @description：线程池
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
        //创建一个拥有5个线程的线程池
//        ExecutorService service = Executors.newFixedThreadPool(5);
        //一个线程池有一个线程
//        ExecutorService service = Executors.newSingleThreadExecutor();
        //线程池中线程数动态扩容
//        ExecutorService service = Executors.newCachedThreadPool();
        //自定义线程池，
//        ExecutorService service = new ThreadPoolExecutor(2,5,60L,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<>(5));
        /**
         * 不被拒绝的最大线程数：
         *  1. 当corePoolSize等于0时，不被拒绝的最大线程数为maximumPoolSize+queueSize-1
         *  2. 当corePoolSize不等于0时，不被拒绝的最大线程数为maximumPoolSize+queueSize
         *
         * 拒绝策略：
         *  1. new ThreadPoolExecutor.AbortPolicy();
         *  将溢出的业务直接拒绝并抛出异常-->RejectedExecutionException
         *  2. new ThreadPoolExecutor.CallerRunsPolicy();
         *  将溢出的业务直接交给调用者线程处理
         *  3. new ThreadPoolExecutor.DiscardPolicy();
         *  将溢出的业务直接丢弃
         *  4. new ThreadPoolExecutor.DiscardOldestPolicy();
         *  发生溢出时，直接将队列头的业务丢弃
         *
         * 最大线程数：
         *  IO密集型 核心线程数 = CPU核数 / （1-阻塞系数）
         *  CPU密集型：核心线程数 = CPU核数 + 1
         *  IO密集型：核心线程数 = CPU核数 * 2
         */
        ExecutorService service = new ThreadPoolExecutor(
                0,
                1,
                50L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(1),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        try {
            for (int i = 0; i < 2; i++) {
                final int x = i + 1;
                service.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t" + x);
                });
                try{TimeUnit.SECONDS.sleep(1);} catch( InterruptedException e){e.printStackTrace();}
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            service.shutdown();
        }
    }
}
